import aiContentless from "./ai.module.less";
import type { PopconfirmProps } from "antd";
import { Input, Popconfirm } from "antd";
import { useState, useEffect, useRef } from "react";
import ReactMarkdown from "react-markdown";
import CodeBlock from "./components/codeBlock/codeBlock";
import rehypeHighlight from "rehype-highlight";
import "highlight.js/styles/atom-one-light.css"; // 选择你喜欢的代码高亮样式
const { TextArea } = Input;
function Ai({
  closeFuAi,
  clearFuAi,
  fullFuScreen,
  setIsFuUserScrolled,
  stopFuStream,
  loadFuMore,
  sendUserFuMsg,
  value,
  showLoading,
  setValue,
  beforeChatTime,
  chatList,
  isUserScrolled,
  done,
}: any) {
  const [focus, setFocus] = useState(false);
  /* const [isUserScrolled, setIsUserScrolled] = useState(false); */
  const oldScrollTop = useRef(0); // 用于保存旧的滚动位置
  const oldScrollHeight = useRef(0); // 用于保存旧的滚动高度
  const chatBodytRef: any = useRef(null);
  const closeAi = () => {
    closeFuAi();
  };
  const confirm: PopconfirmProps["onConfirm"] = () => {
    clearFuAi();
  };
  const onChangeInput = (v: string) => {
    setValue(v);
  };
  const sendUserMsg = () => {
    setIsUserScrolled(false);
    sendUserFuMsg(value);
  };
  const fullScreen = () => {
    fullFuScreen();
  };
  const loadMore = () => {
    loadFuMore();
  };
  const stopStream = () => {
    stopFuStream();
  };
  const setIsUserScrolled = (boolean: boolean) => {
    setIsFuUserScrolled(boolean);
  };
  const pressEnter = (e: any) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault(); // 阻止回车键换行
      if (done) {
        setIsUserScrolled(false);
        sendUserFuMsg(value);
      }
    }
  };
  const scrollToBottom = () => {
    console.log("触发到底");
    if (chatBodytRef.current) {
      const scrollHeight = chatBodytRef.current.scrollHeight;
      const clientHeight = chatBodytRef.current.clientHeight;
      requestAnimationFrame(() => {
        chatBodytRef.current.scrollTop = scrollHeight - clientHeight;
        console.log("触发到底", chatBodytRef.current.scrollTop);
      });
    }
  };
  // 在每次 chatList 更新后滚动到底部
  useEffect(() => {
    console.log("yyyyyyyyyyyyyyyyyyyyyyyyy", isUserScrolled);
    if (!isUserScrolled) {
      scrollToBottom();
    }
  }, [chatList, isUserScrolled]);

  // 监听用户滚动事件
  useEffect(() => {
    const container = chatBodytRef.current;
    const handleScroll = () => {
      // 判断用户是否手动滚动
      const isNearBottom =
        container.scrollTop + container.clientHeight >=
        container.scrollHeight - 50; // 50 是一个阈值，可以根据需要调整

      oldScrollTop.current = container.scrollTop;
      oldScrollHeight.current = container.scrollHeight;

      if (isNearBottom) {
        // 如果用户滚动到接近底部，重置标志位
        setIsUserScrolled(false);
      } else {
        // 否则，表示用户正在手动滚动
        setIsUserScrolled(true);
      }

      if (container.scrollTop <= 20) {
        loadMore();
      }
    };
    container.addEventListener("scroll", handleScroll);
    // 清理事件监听器
    return () => {
      container.removeEventListener("scroll", handleScroll);
    };
  }, []);
  useEffect(() => {
    console.log("监听啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦");
    const container = chatBodytRef.current;
    const newScrollHeight = container.scrollHeight;
    const scrollOffset = newScrollHeight - oldScrollHeight.current;
    setTimeout(() => {
      container.scrollTop = oldScrollTop.current + scrollOffset;
      console.log("topppppppp", container.scrollTop);
    }, 0);
  }, [beforeChatTime]);
  return (
    <>
      <div className={aiContentless.aiContent}>
        <div className="title">
          <div className="leftLogo">
            <img src="/public/img/deepseeklogo.webp" alt="" />
          </div>
          <div className="right_op">
            <Popconfirm
              title="清除全部历史对话"
              description="此操作会清除全部历史对话记录，是否继续?"
              onConfirm={confirm}
              okText="确定"
              cancelText="取消"
            >
              <div className="clear iconfont icon-qingchu"></div>
            </Popconfirm>
            <div
              className="fullScreen iconfont icon-quanping"
              onClick={fullScreen}
            ></div>
            <div
              className="close iconfont icon-guanbi1"
              onClick={closeAi}
            ></div>
          </div>
        </div>
        <div className="centerBody" ref={chatBodytRef}>
          {chatList.length > 0 ? (
            <div className="centerBody_chat">
              {chatList.map((item: any, index: number) => {
                return (
                  <div key={index} className="Items">
                    {item.role === "assistant" ? (
                      <div className="leftAi">
                        <ReactMarkdown
                          rehypePlugins={[rehypeHighlight]}
                          components={{
                            code: CodeBlock, // 使用自定义的代码块组件
                          }}
                        >
                          {item.content}
                        </ReactMarkdown>
                        {item.IsStop ? (
                          <div className="stopStream">已停止生成</div>
                        ) : (
                          ""
                        )}
                      </div>
                    ) : (
                      <div className="rightUser">
                        <div className="message">{item.content}</div>
                      </div>
                    )}
                  </div>
                );
              })}
              {showLoading && (
                <div className="leftAi">
                  <div className="dots">
                    <div></div>
                    <div></div>
                    <div></div>
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="nochatContent">
              <div className="loading">
                <img src="/public/img/AiLoading.png" alt="" />
              </div>
              <div className="titleIcon">
                <div className="hi iconfont icon-nihao"></div>
                <div className="nihao iconfont icon-nihao1"></div>
              </div>
              <div className="tipsContent">
                <div>本服务由DeepSeek提供支持 详情请访问</div>
                <a href="https://chat.deepseek.com/" target="_blank">
                  DeepSeek官网
                </a>
                <div>本站仅实现对API的调用，展示和用户历史对话数据的留存</div>
                <div>Ai的最终回答不代表本站的立场 请注意甄别 谢谢</div>
              </div>
            </div>
          )}
        </div>
        <div className="bottom_input">
          <div className={["input", focus ? "inputActive" : ""].join(" ")}>
            <div className="left">
              <TextArea
                value={value}
                placeholder="请输入相关问题"
                onFocus={() => setFocus(true)}
                onBlur={() => setFocus(false)}
                onPressEnter={(e) => pressEnter(e)}
                onChange={(e) => onChangeInput(e.target.value)}
                autoSize={{ minRows: 1, maxRows: 3 }}
              />
            </div>
            <div className="rightBtn" onClick={sendUserMsg}>
              {done ? (
                value.length > 0 ? (
                  <img src="/public/img/sendBtn.svg" alt="" />
                ) : (
                  <img src="/public/img/sendBtn_n.svg" alt="" />
                )
              ) : (
                <div
                  className="icon iconfont icon-stopo"
                  onClick={stopStream}
                ></div>
              )}
            </div>
          </div>
          <div className="tips">
            请注意辨别，内容由AI模型生成，无法保证准确可靠。
          </div>
        </div>
      </div>
    </>
  );
}

export default Ai;
